package com.g13.virtualpethospital.controller;

import com.g13.virtualpethospital.common.Result;
import com.g13.virtualpethospital.config.AssistantConfig;
import com.g13.virtualpethospital.exceptions.ErnieBotException;
import com.g13.virtualpethospital.service.ErnieBotService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @Title: AiAssistantController
 * @Author yyj1205
 * @Package com.g13.virtualpethospital.controller
 * @Date 16/4/2024 19:25
 * @description: 用于智能助教的控制器
 */
@Slf4j
@RestController
@ApiModel("智能助教相关接口")
@RequestMapping("/assistant")
public class AiAssistantController {
    @Autowired
    private ErnieBotService service;

    @GetMapping("/getSession")
    @ApiOperation("申请缓存数据，用于缓存助教的上下文,请将返回的sessionid缓存")
    @ResponseBody
    public Result<String> getSession(){
        try {
            String sessionId = service.getSession();
            return Result.success(sessionId);
        }
        catch (Exception e){
            return Result.fail("缓存申请失败");
        }
    }

    @GetMapping("/postMessage")
    @ApiOperation("向会话发送数据")
    @ResponseBody
    public Result<String> postMessage(@RequestParam("SessionId") String sessionId,
                                      @RequestParam("Message") String message){
        try {
            String result = service.postMessage(sessionId, message);
            return Result.success(result);
        }catch (ErnieBotException ernieBotException){
            return Result.fail(ernieBotException.getMessage());
        }catch (IOException ioException){
            return Result.fail("鉴权服务器访问失败");
        }
        catch (Exception e){
            return Result.fail("未知异常");
        }
    }
    @GetMapping("/deleteSession")
    @ApiOperation("删除Session数据（虽然有定时删除，但还是尽量调用该接口手动删除）")
    @ResponseBody
    public Result<String> deleteSession(@RequestParam("SessionId") String sessionId){
        try {
            service.deleteSession(sessionId);
            return Result.success("删除成功");
        } catch (ErnieBotException e) {
            return Result.fail("删除失败");
        }
    }
}
